package me.zhengjie.modules.sync.processing;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.SyncTypeEnum;
import com.qiaofang.applet.service.member.domain.Department;
import com.qiaofang.applet.service.member.service.DepartmentService;
import com.qiaofang.applet.service.property.domain.Estate;
import com.qiaofang.applet.service.property.domain.SyncDataQueue;
import com.qiaofang.applet.service.property.service.EstateService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.sync.ProcessingBase;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/*
* 部门数据处理
* */
@Slf4j
@Service
public class DepartmentSyncProcessing extends ProcessingBase {

    public DepartmentSyncProcessing(){
        setDataType(SyncTypeEnum.DEPT.getSyncType());
    }

    @Autowired
    DepartmentService departmentService;

    @Override
    protected void processing(SyncDataQueue syncDataQueue) {
        String batchContent=syncDataQueue.getBatchContent();
        List<Department> list= JSON.parseArray(batchContent, Department.class);
        if(null==list){
            log.info("processing Estate is null");
            return;
        }
        list.stream().forEach(item->{
            saveDepartment(item,syncDataQueue);
        });
    }

    private void saveDepartment(Department item,SyncDataQueue syncDataQueue){
        Department department= departmentService.findByDeptUuidAndCompanyUuid(item.getDeptUuid(),syncDataQueue.getCompanyUuid());
        if(!Objects.isNull(item.getDeleted()) && item.getDeleted()){
            if (!Objects.isNull(department)) {
                departmentService.deleteById(department.getId());
            }
            return;
        }
        if(Objects.isNull(department)){
            department=new Department();
        }
        //复制属性
        String[] ignoreProperties=new String[] {"id","createBy","updateBy","createTime","updateTime"};
        BeanUtils.copyProperties(item,department,ignoreProperties);
        department.setCompanyUuid(syncDataQueue.getCompanyUuid());
        department.setCityCode(syncDataQueue.getCityCode());
        department.setCorporationCode(syncDataQueue.getCorporationCode());
        department.setUpdateTime(new Date());
        department.setRelationUpdate(true);
        department.setLastSyncDate(new Date(System.currentTimeMillis() - DateUtil.DAY_MILLISECONDS));
        try {
            departmentService.save(department);
        } catch (Exception e) {
            log.error("saveDepartment error",e);
            //记录错误日志
            this.saveErrorLog(JSON.toJSONString(department),e.getMessage(),syncDataQueue);
        }
    }
}
